<?php

/**
 * Транслятор объектов в XML-таблицы
 */
class XMLTranslator implements iXMLTranslator {
	
	public function __construct () {}
	
	/**
	 * Возврашает строку в виде XML таблицы страницы
	 * @param ModuleResponse $oResponse
	 * @return string
	 */
	public function render (ModuleResponse $oResponse) {
		header ('Content-type: text/xml; charset=utf-8');
		
		$xml = $this->buildPageResponse ($oResponse);
		
		return $xml->saveXML ();
	}
	
	/**
	 * Строит дерево страницы
	 * @param ModuleResponse $oResponse
	 * @return DOMDocument
	 */
	public function buildPageResponse (ModuleResponse $oResponse) {
		$cmsController = CMSController::getInstance ();
		
		$xml = new DOMDocument ('1.0', 'utf-8');
		
		$dataNode = $xml->createElement ('data');
		
		$dataNode->setAttribute ('base-uri', HTTP_HOST);
		$dataNode->setAttribute ('module', $cmsController->getCurrentModuleName ());
		$dataNode->setAttribute ('method', $cmsController->getCurrentMethod ());
		$dataNode->setAttribute ('user-id', ExplaySession::getUserId ());
		$dataNode->setAttribute ('user-group', userGroup (ExplaySession::getUser()->getValue ('group')));
		$dataNode->setAttribute ('query-string', GET2String ($_GET));
		$dataNode->setAttribute ('lang', LANG);
		$dataNode->setAttribute ('scode', SCODE);
		$dataNode->setAttribute ('title',  CMSController::getPageTitle ());
		
		// Response
		$dataNode->appendChild ($this->getModuleResponse ($xml, $oResponse));
		
		$xml->appendChild ($dataNode);
		
		return $xml;
	}
	
	/**
	 * Возвращает экземлпяр класса ModuleResponse в воде объекта DOMElement
	 * @param ModuleResponse $oResponse
	 * @return DOMElement
	 */
	public function getModuleResponse (DOMDocument $xml, ModuleResponse $oResponse) {
		$aObjects = $oResponse->getObjects ();
		
		$responseNode = $xml->createElement ('response');
		
		$aAttributes = $oResponse->getAttributes ();
		
		foreach ($aAttributes as $name => $value) {
			$responseNode->setAttribute ($name, $value);
		}
		
		foreach ($aObjects as $item) {
			if (is_string ($item)) {
				$responseNode->appendChild ($xml->createElement ('value', $item));
			} elseif (is_object ($item)) {
				$responseNode->appendChild ($item->__toXML ($xml));
			} else {
				$responseNode->appendChild ($xml->createElement ('error', 'Invalid object type in module response. Returned object of type "' . gettype($item) .'", expected object or string.'));
			}
		}

		return $responseNode;
	}

}